#!/bin/sh
#--------------------------------------
# fcitx-config
#

# from xdg-open

detectDE()
{
    if [ x"$KDE_FULL_SESSION" = x"true" ]; then DE=kde;
    elif [ x"$GNOME_DESKTOP_SESSION_ID" != x"" ]; then DE=gnome;
    elif `dbus-send --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.GetNameOwner string:org.gnome.SessionManager > /dev/null 2>&1` ; then DE=gnome;
    elif xprop -root _DT_SAVE_MODE 2> /dev/null | grep ' = \"xfce4\"$' >/dev/null 2>&1; then DE=xfce;
    fi
}

run_kde()
{
    command=`which kcmshell4 2>&1`
    haskde=0
    if [ $? -eq 0 ]; then
        checkinstalled=`$command --list | grep -c kcm_fcitx`
        if [ "x$checkinstalled" != "x0" ]; then
            haskde=1
        fi
    fi

    if [ $haskde = "1" ]; then
        exec $command kcm_fcitx
    else
        run_gtk
    fi
}

run_gtk()
{
    command=`which fcitx-config-gtk 2>&1`
    if [ $? -eq 0 ]; then
        exec $command
    else
        run_xdg
    fi
}

run_gtk3()
{
    command=`which fcitx-config-gtk3 2>&1`
    if [ $? -eq 0 ]; then
        exec $command
    else
        run_gtk
    fi
}

run_xdg()
{
    command=`which xdg-open`
    if [ $? -eq 0 ]; then
        exec $command $HOME/.config/fcitx/config
    else
        exit 0
    fi
}

if [ ! -n "$DISPLAY" ]; then
    [ -n "$EDITOR" ] && which $EDITOR > /dev/null 2>&1 && exec $EDITOR $HOME/.config/fcitx/config
    [ -n "$VISUAL" ] && which $VISUAL > /dev/null 2>&1 && exec $VISUAL $HOME/.config/fcitx/config
    echo 'Please run it under X, or set $EDITOR or $VISUAL'
    exit 0
fi

detectDE

case "$DE" in
    kde)
        run_kde
        ;;
    *)
        run_gtk3
        ;;
esac
